<template>
    <el-scrollbar ref="myScrollbar" style="overflow: hidden">
        <div class="record_list_cls">
            <record-item v-for="(t,i) in finalRecords" :key="i"
                         :record="t"></record-item>
        </div>
    </el-scrollbar>
</template>

<script>
  import * as _ from 'underscore'
  import _subject from '../../assets/utils/subject'
  import RecordItem from './RecordItem'
  import http from '../../assets/utils/http'
  import comm from '../../assets/utils/comm'

  export default {
    name: 'RecordList',
    props: {
      who: {
        type: String,
        default: '1'
      },
      side: {
        type: String,
        default: 'platform'
      },
      commId: {
        type: Number,
        default: 0
      },
      toId: {
        type: Number,
        default: 0
      },
      createTime: {
        type: Number,
        default: 0
      }
    },
    computed: {
      finalRecords() {
        this.judgeShowTime()
        return this.communication.records
      }
    },
    watch: {
      commId: {
        immediate: true,
        handler() {
          if (this.commId) {
            //清除未读消息标记
            this.clearUnread()
            //重新开始分页
            this.page.current = 0
            this.communication.records.splice(0, this.communication.records.length)
            this.loadRecords()
          }
        }
      }
    },
    methods: {
      getNewMessage(commId, unread) {
        this.$emit('new-msg', commId, unread)
      },
      scrollDown() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
          this.page.lastHeight = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      scrollPercent() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight - this.page.lastHeight
          this.page.lastHeight = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      onScrollTop() {
        this.loadRecords()
      },
      judgeShowTime() {
        //是否显示时间，3min以内的时间不显示
        for (let i = 1; i < this.communication.records.length; i++) {
          const last = this.communication.records[i - 1]
          const current = this.communication.records[i]
          current.showTimeQ = current.time - last.time > 3 * 60 * 1000
        }
        //图标
        _.each(this.communication.records, o => {
          o.icon = o.meQ ? _subject.getPlatformIcon() : comm.toIcon
        })
      },
      loadRecords() {
        this.lAxios({
          method: 'post', //方法
          url: '/platform/selectComDetailInfoByPlatfromId.do',
          params: {
            comID: this.commId,
            // state: Number(this.who),
            currPageNo: this.page.current + 1,
            pageSize: this.page.size
          }
        }).then(res => {
          res = res.data
          console.log('selectComDetailInfoByPlatfromId', res)
          if (res && res.status === 0) {
            const page = res.data.pageInfo
            this.page.total = page.total
            this.page.current = page.pageNum
            if (page.list.length > 0) {
              let temp = _.map(page.list, t => {
                const o = JSON.parse(t.content)
                const state = Number(o.send_state)
                let type = state
                const time = Date.parse(t.time)
                return {
                  showTimeQ: false,
                  meQ: o.mainCom === this.side,
                  content: o.content,
                  type: type,
                  time: time,
                  job: type === 5 ? JSON.parse(o.content) : {},
                  talent: type === 4 ? JSON.parse(o.content) : {},
                  hello: type === 6 ? content : {}
                }
              })
              temp = _.sortBy(temp, t => {
                return t.time
              })
              if (this.page.current === 1) {
                this.communication.records = temp
                this.scrollDown()
              } else {
                this.communication.records = temp.concat(this.communication.records)
                this.scrollPercent()
              }
            } else {
              this.page.current -= 1
            }
          }
        })
      },
      clearUnread() {
        const str = {
          'comid': String(this.commId),
          'type': 'CLEAR',
          'mainCom': this.side,
          'mainUserId': String(_subject.getPlatformId())
        }
        _subject.ws.next(str)
      },
      sendContent(text, type) {
        const str = {
          'toCom': this.who === '1' ? 'talent' : 'company',
          'toUserId': String(this.toId),
          'comid': String(this.commId),
          'type': 'SINGLE_SENDING',
          'content': text,
          'mainUserId': _subject.getPlatformId(),
          'mainCom': this.side,
          'send_state': String(type)
        }
        _subject.ws.next(str)
        //添加到本地记录
        this.communication.records.push({
          type: type,
          content: text,
          meQ: true,
          time: new Date().format('yyyy-MM-dd hh:mm:ss'),
          job: type === 5 ? JSON.parse(text) : {},
          talent: type === 4 ? JSON.parse(text) : {},
          hello: type === 6 ? content : {}
        })
        this.scrollDown()
      },
      sendText(currentInput) {
        const trim = currentInput.trim()
        if (trim) {
          this.sendContent(trim.replace(/\n/g, '<br/>'), 0)
        }
      }
    },
    data() {
      return {
        data: '',
        wsSub: null,
        page: {
          current: 0,
          size: 10,
          total: 0,
          lastHeight: 0//加载新页之前scrollbar的高度
        },
        communication: {
          records: [
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' },
            { meQ: true, type: 0, content: 'abc' }
          ]
        }
      }
    },
    components: { RecordItem },
    created() {
      let self = this
      this.wsSub = _subject.ws.subscribe({
        next(t) {
          console.log('new company ws message', t)
          if (t.status === 200) {
            let m = t.data.type
            if (m === 'SINGLE_SENDING') {
              let commId = t.data.comid
              let mainId = t.data.mainUserId
              let toId = t.data.toUserId//对方发送的消息
              //通知收到父组件消息
              self.getNewMessage(Number(t.data.comid), Number(t.data.unread))
              if (commId === String(self.commId) && toId === String(_subject.getPlatformId()) && mainId === String(self.toId)) {
                const content = t.data.content
                const type = Number(t.data.send_state)
                self.communication.records.push({
                  type: type,
                  content: content,
                  meQ: false,
                  time: new Date().format('yyyy-MM-dd hh:mm:ss'),
                  job: type === 5 ? JSON.parse(content) : {},
                  talent: type === 4 ? JSON.parse(content) : {},
                  hello: type === 6 ? content : {}
                })
                console.log('company records', self.communication.records)
              }
              self.scrollDown()
            }
          } else if (t.status === -1) {
            window._$vm.$message.warning('对方不在线，可能无法立即回复您')
          }
        }
      })
    },
    destroyed() {
      if (this.wsSub) {
        this.wsSub.unsubscribe()
      }
    },
    mounted() {
      this.$refs['myScrollbar'].wrap.onscroll = e => {
        if (e.target.scrollTop === 0) {
          this.onScrollTop()
        }
      }
    }
  }
</script>

<style scoped>

</style>